package com.demo.lifeinfo.common.news;

import android.content.Intent;
import android.os.Bundle;
import android.text.TextUtils;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;

import androidx.appcompat.widget.Toolbar;
import androidx.constraintlayout.widget.ConstraintLayout;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import com.chad.library.adapter.base.BaseQuickAdapter;
import com.chad.library.adapter.base.BaseViewHolder;
import com.demo.lifeinfo.R;
import com.demo.lifeinfo.adapter.MyNineImageAdapter;
import com.demo.lifeinfo.app.XBaseActivity;
import com.demo.lifeinfo.common.sign.LoginActivity;
import com.demo.lifeinfo.entity.Comment;
import com.demo.lifeinfo.entity.News;
import com.demo.lifeinfo.entity.User;
import com.demo.lifeinfo.model.GlideApp;
import com.demo.lifeinfo.widget.CustomEditPopup;
import com.flyco.roundview.RoundTextView;
import com.google.android.material.appbar.AppBarLayout;
import com.jaeger.ninegridimageview.NineGridImageView;
import com.lxj.xpopup.XPopup;

import java.util.List;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
import cn.bmob.v3.BmobQuery;
import cn.bmob.v3.BmobUser;
import cn.bmob.v3.datatype.BmobPointer;
import cn.bmob.v3.datatype.BmobRelation;
import cn.bmob.v3.exception.BmobException;
import cn.bmob.v3.listener.FindListener;
import cn.bmob.v3.listener.UpdateListener;

/**
 * created by Raymond
 * on 2019-05-04
 */
public class NewsDetailAc extends XBaseActivity {

    News news;

    @BindView(R.id.toolbar_back)
    ImageView toolbarBack;
    @BindView(R.id.textView3)
    TextView textView3;
    @BindView(R.id.toolbar_right_btn)
    RoundTextView toolbarRightBtn;
    @BindView(R.id.toolbar)
    Toolbar toolbar;
    @BindView(R.id.appBarLayout)
    AppBarLayout appBarLayout;
    @BindView(R.id.linearLayout)
    LinearLayout linearLayout;
    @BindView(R.id.textView2)
    TextView textView2;
    @BindView(R.id.nineGridImageView)
    NineGridImageView nineGridImageView;
    @BindView(R.id.head_img)
    ImageView headImg;
    @BindView(R.id.btn_1)
    ConstraintLayout btn1;
    @BindView(R.id.btn_2)
    ConstraintLayout btn2;
    @BindView(R.id.btn_3)
    ConstraintLayout btn3;
    @BindView(R.id.nick_name)
    TextView nickName;
    @BindView(R.id.love_icon)
    ImageView loveIcon;
    @BindView(R.id.comment_list)
    RecyclerView commentList;

    BaseQuickAdapter<Comment, BaseViewHolder> adapter;

    boolean isLove = false;
    @BindView(R.id.textView)
    TextView textView;

    @Override
    protected int getLayoutId() {
        return R.layout.activity_news_detail;
    }

    @Override
    protected void initView() {
        news = (News) getIntent().getSerializableExtra("news");
        textView3.setText("详情");
        GlideApp.with(this)
                .load(news.getAuthor().getAvatar() == null ? R.drawable.ic_launcher_background : news.getAuthor().getAvatar().getFileUrl())
                .centerCrop()
                .placeholder(R.mipmap.ic_launcher)
                .error(R.mipmap.ic_launcher)
                .circleCrop()
                .into(headImg);
        nickName.setText(TextUtils.isEmpty(news.getAuthor().getNickeName()) ? "匿名" : news.getAuthor().getNickeName());
        textView2.setText("   " + news.getContent());
        MyNineImageAdapter imageAdapter = new MyNineImageAdapter();
        nineGridImageView.setAdapter(imageAdapter);
        nineGridImageView.setImagesData(news.getImgs());

        adapter = new BaseQuickAdapter<Comment, BaseViewHolder>(R.layout.item_comment) {
            @Override
            protected void convert(BaseViewHolder helper, Comment item) {
                GlideApp.with(NewsDetailAc.this)
                        .load(item.getPublisher().getAvatar() == null ? R.drawable.ic_launcher_background : item.getPublisher().getAvatar().getFileUrl())
                        .centerCrop()
                        .placeholder(R.mipmap.ic_launcher)
                        .error(R.mipmap.ic_launcher)
                        .circleCrop()
                        .into((ImageView) helper.getView(R.id.head_img));
                helper.setText(R.id.tv_nickname, TextUtils.isEmpty(item.getPublisher().getNickeName()) ? "匿名" : item.getPublisher().getNickeName());
                helper.setText(R.id.tv_content, item.getText());
                helper.setText(R.id.time, item.getCreatedAt());
                if (isLogin()) {
                    if (BmobUser.getCurrentUser(User.class).getObjectId().equals(item.getPublisher().getObjectId())) {
                        helper.setVisible(R.id.btn_delet_comment, true);
                    } else {
                        helper.setVisible(R.id.btn_delet_comment, false);
                    }
                } else {
                    helper.setVisible(R.id.btn_delet_comment, false);
                }
                helper.addOnClickListener(R.id.btn_delet_comment);
            }

        };
        adapter.setOnItemChildClickListener(new BaseQuickAdapter.OnItemChildClickListener() {
            @Override
            public void onItemChildClick(BaseQuickAdapter adapter, View view, int position) {

                deletComment((Comment) adapter.getItem(position), position);
            }
        });
        View view = LayoutInflater.from(this).inflate(R.layout.view_empty, null);
        adapter.setEmptyView(view);
        commentList.setLayoutManager(new LinearLayoutManager(NewsDetailAc.this));
        commentList.setAdapter(adapter);
    }

    @Override
    protected void initData() {
        if (isLogin()) {
            islove();
        }
        getComment();

    }

    private void dianzan(News news, ImageView view) {
        if (BmobUser.getCurrentUser(User.class) != null) {
            BmobRelation relation = new BmobRelation();
            relation.add(BmobUser.getCurrentUser(User.class));
            news.setLiks(relation);
            news.update(new UpdateListener() {
                @Override
                public void done(BmobException e) {
                    if (e == null) {
                        shoucang(news);
                        isLove = true;
                        GlideApp.with(NewsDetailAc.this).load(R.drawable.ic_aixin_select).into(view);
                    } else {
                        Log.e("xiaoqiang", e.getErrorCode() + "===msg:" + e.getMessage());
                    }
                }
            });
        } else {
            startActivity(new Intent(NewsDetailAc.this, LoginActivity.class));
        }
    }

    private void shoucang(News news) {
        BmobRelation relation = new BmobRelation();
        relation.add(news);
        User ur = BmobUser.getCurrentUser(User.class);
        ur.setMyLove(relation);
        ur.update(new UpdateListener() {
            @Override
            public void done(BmobException e) {
                if (e == null) {

                } else {

                }
            }
        });

    }

    private void noshoucang(News news) {
        BmobRelation relation = new BmobRelation();
        relation.remove(news);
        User ur = BmobUser.getCurrentUser(User.class);
        ur.setMyLove(relation);
        ur.update(new UpdateListener() {
            @Override
            public void done(BmobException e) {
                if (e == null) {

                } else {

                }
            }
        });

    }

    private void quxiao(News news, ImageView view) {
        if (BmobUser.getCurrentUser(User.class) != null) {
            BmobRelation relation = new BmobRelation();
            relation.remove(BmobUser.getCurrentUser(User.class));
            news.setLiks(relation);
            news.update(new UpdateListener() {
                @Override
                public void done(BmobException e) {
                    if (e == null) {
                        noshoucang(news);
                        isLove = false;
                        GlideApp.with(NewsDetailAc.this).load(R.drawable.ic_aixin_unselect).into(view);
                    } else {
                        Log.e("xiaoqiang", e.getErrorCode() + "===msg:" + e.getMessage());
                    }
                }
            });
        } else {
            startActivity(new Intent(NewsDetailAc.this, LoginActivity.class));
        }
    }

    private void islove() {
        BmobQuery<User> query = new BmobQuery<>();
        query.addWhereRelatedTo("liks", new BmobPointer(news));
//        query.addWhereEqualTo("objectId", BmobUser.getCurrentUser(User.class).getObjectId());
        query.findObjects(new FindListener<User>() {
            @Override
            public void done(List<User> list, BmobException e) {
                if (e == null) {
                    if (list.size() > 0) {
                        for (User user : list) {
                            if (BmobUser.getCurrentUser(User.class).getObjectId().equals(user.getObjectId())) {
                                isLove = true;
                                GlideApp.with(NewsDetailAc.this).load(R.drawable.ic_aixin_select).into(loveIcon);
                            }
                        }

                    } else {

                    }
                } else {
                    showError(e.getMessage());
                }
                //17521004436
            }
        });
    }

    private void getComment() {
        BmobQuery<Comment> query = new BmobQuery<>();
        query.order("-createdAt").include("publisher").addWhereEqualTo("news", news).findObjects(new FindListener<Comment>() {
            @Override
            public void done(List<Comment> list, BmobException e) {
                if (e == null) {
                    adapter.setNewData(list);
                } else {
                    showError(e.getMessage());
                }
            }
        });
    }

    private void deletComment(Comment comment, int index) {
        comment.delete(new UpdateListener() {
            @Override
            public void done(BmobException e) {
                if (e == null) {
                    adapter.remove(index);
                } else {

                }
            }
        });
    }

    @OnClick({R.id.btn_1, R.id.btn_2, R.id.btn_3})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.btn_1:
                break;
            case R.id.btn_2:
                new XPopup.Builder(NewsDetailAc.this)
                        .asCustom(new CustomEditPopup(NewsDetailAc.this, news))
                        .show();
                break;
            case R.id.btn_3:
                if (isLove) {
                    quxiao(news, loveIcon);
                } else {
                    dianzan(news, loveIcon);
                }

                break;
        }
    }


    @OnClick(R.id.toolbar_back)
    public void onViewClicked2() {
        onBackPressed();
    }
}
